//
//  FilePreviewController.swift
//  GreenDeal
//
//  Created by Moennig Q on 24/11/2022.
//

import UIKit
import QuickLook
class FilePreviewController: UIViewController,QLPreviewControllerDataSource {
    var imagesArray: Array<CheckListImageDBModel>!
    var fileURLs: [URL]!
    var currentIndex: Int = 0
    var previewController: QLPreviewController!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.fileURLs = self.loadAllFileToLocal(imagesArray)
        if self.fileURLs.count > 0{
            previewController = QLPreviewController()
            previewController.dataSource = self
            previewController.view.frame = self.view.frame
            previewController.currentPreviewItemIndex = 0
            self.addChild(previewController)
            self.view.addSubview(previewController.view)
        }
    }
    //QLPreviewControllerDataSource
    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return fileURLs.count
    }
    //
    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
        
        return fileURLs[index] as QLPreviewItem
    }
    //MARK: - 获取来自服务器的pdf文件存储到本地
    private func loadAllFileToLocal(_ list: Array<CheckListImageDBModel>)->[URL]{
        var resultList = [URL]()
        for iModel in list{
            let imagePathStr = iModel.image
            var filePath: URL?
            if imagePathStr.contains("http"){//server
                filePath = URL(string: imagePathStr)
            }else{//local
                filePath = URL(fileURLWithPath: imagePathStr)
            }
            guard let fileURL = filePath else { continue  }
           
            do {
                let fileName = fileURL.lastPathComponent
                let data = try Data(contentsOf: fileURL)
                // Give the file a name and append it to the file path
                let localFileURL = FileManager().temporaryDirectory.appendingPathComponent(fileName)
                // Write the pdf to disk in the temp directory
                try data.write(to: localFileURL, options: .atomic)
                // Make sure the file can be opened and then present the pdf
                if QLPreviewController.canPreview(localFileURL as QLPreviewItem) {
                    resultList.append(localFileURL)
                }
            }catch {
                // cant find the url resource
            }
        }
        return resultList
    }
}

